package st.business.tepth.business.user.busnumber.workholder.maintain.work.content;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.DiagnoseBean;
import st.business.tepth.business.bean.MaintainNotWorkWrapper;
import st.business.tepth.business.bean.PersonBean;
import st.business.tepth.business.bean.PickGoods;
import st.business.tepth.business.bean.RepairTaskBean;
import st.business.tepth.business.event.GoodsEvent;
import st.business.tepth.business.event.ReloadMaintainWorkDataEvent;
import st.business.tepth.business.event.StartBrotherEvent;
import st.business.tepth.business.goodsorder.GoodsOrderDelegate;
import st.business.tepth.business.user.busnumber.workholder.adapter.TroubleWorkPersonAdapter;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogConfirmProgram;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogMaintainNotWork;
import st.business.tepth.business.user.busnumber.workholder.maintain.work.WorkDelegate;
import st.business.tepth.business.user.busnumber.workholder.maintain.work.content.repairwork.RepairWorkDelegate;
import st.business.tepth.business.user.busnumber.workholder.maintain.work.content.standardwork.StandardWorkDelegate;
import st.business.tepth.business.user.busnumber.workholder.repair.work.content.RepairDataConvert;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.mvp.MvpFragment;
import st.shadow.library.core.util.utilcode.util.ScreenUtils;
import st.shadow.library.ui.dialog.DialogLoader;
import st.shadow.library.ui.dialog.IDialogClickListener;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-03-23 09:46
 * 保养作业界面
 */

public class MaintainWorkDelegate extends MvpFragment<MaintainWorkPresenter>
        implements MaintainWorkContract.View {
    public static MaintainWorkDelegate newInstance(int repairId,
                                                   int vehicleSeriesId,
                                                   int operationState,
                                                   int position) {
        Bundle bundle = new Bundle();
        bundle.putInt("repairId", repairId);
        bundle.putInt("position", position);
        bundle.putInt("vehicleSeriesId", vehicleSeriesId);
        bundle.putInt("operationState", operationState);
        MaintainWorkDelegate delegate = new MaintainWorkDelegate();
        delegate.setArguments(bundle);
        return delegate;
    }

    private int mVehicleSeriesId;
    private int mRepairId;
    @BindView(R2.id.radio_group)
    RadioGroup mRadioGroup;
    @BindView(R2.id.layout_container)
    ConstraintLayout mLayoutContainer;
    @BindView(R2.id.recycler_view_person)
    RecyclerView mRecyclerViewPerson;
    @BindView(R2.id.tv_done)
    TextView mTvDone;
    @BindView(R2.id.tv_confirm)
    TextView mTvConfirm;
    private RepairWorkDelegate mRepairWorkDelegate;
    private StandardWorkDelegate mStandardWorkDelegate;
    private int mRepairTaskId;
    private DialogLoader mDialogLoader;
    private int mCheckId;
    private int mOperationState;
    private int mMyStatus;
    private int mPosition;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("MaintainWorkDelegate", "onCreate");
        Bundle bundle = getArguments();
        if (bundle != null) {
            mRepairId = bundle.getInt("repairId");
            mVehicleSeriesId = bundle.getInt("vehicleSeriesId");
            mOperationState = bundle.getInt("operationState");
            mPosition = bundle.getInt("position");
        }
    }

    @Override
    public MaintainWorkPresenter getPresenter() {
        return new MaintainWorkPresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_maitain_work_holder;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mDialogLoader = new DialogLoader(_mActivity);
        mRecyclerViewPerson.setLayoutManager(new LinearLayoutManager(_mActivity,
                LinearLayoutManager.HORIZONTAL, false));
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (mRepairWorkDelegate != null && mStandardWorkDelegate != null) {
                    if (checkedId == R.id.rb_repair) {
                        showHideFragment(mRepairWorkDelegate, mStandardWorkDelegate);
                    } else {
                        showHideFragment(mStandardWorkDelegate, mRepairWorkDelegate);
                    }
                }
                mCheckId = checkedId;
            }
        });
        mCheckId = R.id.rb_maintain;
        EventBus.getDefault().register(this);
    }

    public void loadData() {
        mPresenter.getWorkData(UserManager.getInstance().getToken(),
                mRepairId, mVehicleSeriesId);
        addTopView(R.layout.view_loading, mLayoutContainer, 1050, 600);
    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        loadData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void showRepairTask(RepairTaskBean repairTaskBean) {
        if (repairTaskBean != null) {
            int status = repairTaskBean.getMy_status();
            mMyStatus = status;
            if (mOperationState == 1) {
                changeButtonState(status);
            } else {
                mTvDone.setVisibility(View.GONE);
                mTvConfirm.setVisibility(View.GONE);
                //不可操作的时候随便给一个大于3的值界面就不可操作
                status = 7;
            }
            List<PersonBean> personBeans = repairTaskBean.getWorkerList();
            if (personBeans != null) {
                mRepairTaskId = repairTaskBean.getId();
                mRecyclerViewPerson.setAdapter(
                        new TroubleWorkPersonAdapter(R.layout.item_trouble_work_person, personBeans));
            }
            mRepairWorkDelegate = findChildFragment(RepairWorkDelegate.class);
            mStandardWorkDelegate = findChildFragment(StandardWorkDelegate.class);
            if (mRepairWorkDelegate == null || mStandardWorkDelegate == null) {
                mRepairWorkDelegate = RepairWorkDelegate.
                        newInstance(repairTaskBean.getFaultPhenomenonList(),
                                status,
                                mRepairId, repairTaskBean.getId(),
                                mVehicleSeriesId);
                mStandardWorkDelegate =
                        StandardWorkDelegate.newInstance(mRepairId,
                                repairTaskBean.getId(),
                                repairTaskBean.getCategoryList(),
                                personToString(personBeans), status);
                loadMultipleRootFragment(R.id.layout_content, 0,
                        mStandardWorkDelegate,
                        mRepairWorkDelegate);
            } else {
                mRepairWorkDelegate.resetData(repairTaskBean.getFaultPhenomenonList(),
                        status,
                        mRepairId, repairTaskBean.getId(), mVehicleSeriesId);
                mStandardWorkDelegate.resetData(mRepairId,
                        repairTaskBean.getId(),
                        repairTaskBean.getCategoryList(),
                        personToString(personBeans), status);
            }
            changeTroubleCount(repairTaskBean.getFaultPhenomenonList());
        }
        removeTopView(mLayoutContainer);
    }

    public void changeTroubleCount(ArrayList<RepairTaskBean.FaultPhenomenonListBean>
                                           faultPhenomenonList) {
        WorkDelegate workDelegate = (WorkDelegate) getParentFragment();
        if (workDelegate != null) {
            workDelegate.changeTroubleCount(getUnResolveCount(faultPhenomenonList),
                    mPosition);
        }
    }

    private int getUnResolveCount(ArrayList<RepairTaskBean.FaultPhenomenonListBean>
                                          faultPhenomenonList) {
        int count = 0;
        if (faultPhenomenonList != null && !faultPhenomenonList.isEmpty()) {
            for (RepairTaskBean.FaultPhenomenonListBean faultPhenomenonListBean :
                    faultPhenomenonList) {
                ArrayList<DiagnoseBean> diagnoseBeans =
                        faultPhenomenonListBean.getFaultDiagnosticTemporaryList();
                if (diagnoseBeans == null || diagnoseBeans.isEmpty()) {

                    count++;
                } else {
                    for (DiagnoseBean diagnoseBean : diagnoseBeans) {
                        if (diagnoseBean.getPlanList() == null ||
                                diagnoseBean.getPlanList().isEmpty()) {
                            count++;
                        }
                    }
                }
            }
        }
        return count;
    }

    private void changeButtonState(int status) {
        switch (status) {
            case 0:
            case 1:
                mTvDone.setVisibility(View.GONE);
                mTvConfirm.setVisibility(View.VISIBLE);
                mTvConfirm.setBackground(_mActivity.getResources()
                        .getDrawable(R.drawable.selector_btn_operation));
                mTvConfirm.setEnabled(true);
                mTvConfirm.setText("确认方案");
                mTvConfirm.setTextColor(Color.parseColor("#333333"));
                break;
            case 2:
                mTvDone.setVisibility(View.VISIBLE);
                mTvDone.setVisibility(View.VISIBLE);
                mTvDone.setBackground(_mActivity.getResources()
                        .getDrawable(R.drawable.selector_btn_operation));
                mTvDone.setEnabled(true);
                mTvDone.setText("作业完成");
                mTvDone.setTextColor(Color.parseColor("#333333"));
                mTvConfirm.setTextColor(Color.parseColor("#333333"));
                mTvConfirm.setVisibility(View.VISIBLE);
                mTvConfirm.setBackground(_mActivity.getResources()
                        .getDrawable(R.drawable.selector_btn_operation));
                mTvConfirm.setEnabled(true);
                mTvConfirm.setText("确认方案");
                mTvConfirm.setTextColor(Color.parseColor("#333333"));
                break;
            case 3:
                mTvDone.setVisibility(View.VISIBLE);
                mTvConfirm.setVisibility(View.GONE);
                mTvDone.setText("取消作业完成");
                if (mRepairWorkDelegate != null) {
                    mRepairWorkDelegate.workHasDone();
                }
                mTvDone.setBackground(_mActivity.getResources()
                        .getDrawable(R.drawable.selector_btn_operation));
                mTvDone.setTextColor(Color.parseColor("#333333"));
                mTvDone.setEnabled(true);
                break;
        }
    }

    @Override
    public void showError(String msg) {
        mDialogLoader.stopProgressWithFailed("提交失败", msg);
    }

    private String personToString(List<PersonBean> list) {
        StringBuilder name = new StringBuilder();
        if (list != null) {
            for (PersonBean personBean : list) {
                name.append(personBean.getUser_name()).append("(").append(personBean.getJob_no()).append(") ");
            }
        }
        return name.toString();
    }

    @OnClick(R2.id.tv_confirm)
    public void confirmProgram() {
        String taskItemList = "";
        String maintainList = "";
        if (mRepairWorkDelegate != null) {
            taskItemList = new RepairDataConvert().
                    programListToJson(mRepairWorkDelegate.
                            getProgramList(), mRepairId, mVehicleSeriesId, 1);
        }
        if (mStandardWorkDelegate != null) {
            maintainList = JSON.toJSONString(mStandardWorkDelegate.getSelectList());
        }
        mDialogLoader.showProgressDialog(false, "正在提交", "请稍候...");
        mPresenter.commitProgram(UserManager.getInstance().getToken(),
                mRepairId, mRepairTaskId, mVehicleSeriesId, taskItemList, maintainList);
    }

    @OnClick(R2.id.tv_done)
    public void onWorkDone() {
        if (mMyStatus == 3) {
            //取消作业完成
            mDialogLoader.showProgressDialog(false, "正在提交",
                    "请稍候");
            mPresenter.cancelFinishWork(UserManager.getInstance().getToken(),
                    mRepairId, mRepairTaskId, mVehicleSeriesId);
        } else {
            if (mStandardWorkDelegate != null) {
                int confirmCount = mStandardWorkDelegate.getConfirmCount();
                if (confirmCount != -1) {
                    mDialogLoader.showWarning("提示",
                            "您将完成" + confirmCount + "项该系保养标准作业项，是否确认",
                            new IDialogClickListener() {
                                @Override
                                public void onClick() {
                                    mDialogLoader.changeToProgressType("正在提交");
                                    mPresenter.submitFinishWork(UserManager.getInstance().getToken(),
                                            mRepairId,
                                            mRepairTaskId,
                                            mVehicleSeriesId);
                                }
                            });
                } else {
                    mDialogLoader.showProgressDialog(false, "正在提交",
                            "请稍后...");
                    mPresenter.submitFinishWork(UserManager.getInstance().getToken(),
                            mRepairId,
                            mRepairTaskId,
                            mVehicleSeriesId);
                }
            } else {
                mDialogLoader.showProgressDialog(false, "正在提交",
                        "请稍后...");
                mPresenter.submitFinishWork(UserManager.getInstance().getToken(),
                        mRepairId,
                        mRepairTaskId,
                        mVehicleSeriesId);
            }
        }
    }

    @Override
    public void submitFinishSucceed() {
        mDialogLoader.stopProgressWithSuccess("提交成功",
                null, new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        mDialogLoader.clearDialog();
                        EventBus.getDefault().post(new ReloadMaintainWorkDataEvent(mRepairId));
                    }
                });
    }

    @Override
    public void showPickGoods(final List<PickGoods> list) {
        _mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (list != null && !list.isEmpty()) {
                    mDialogLoader.clearDialog();
                    DialogConfirmProgram dialogDeleteProgram = new DialogConfirmProgram(_mActivity,
                            list,
                            new OnItemChooseListener<String>() {
                                @Override
                                public void onChoose(String o) {
                                    //发起领料
                                    mDialogLoader.showProgressDialog(true,
                                            "正在提交", "请稍候...");
                                    mPresenter.pickGoods(UserManager.getInstance().getToken(),
                                            mRepairId, mVehicleSeriesId,
                                            o);
                                }
                            });
                    Window dialogWindow = dialogDeleteProgram.getWindow();
                    if (dialogWindow != null) {
                        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                        lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
                        lp.height = ScreenUtils.getScreenHeight() * 820 / 1024; // 高度
                        dialogWindow.setGravity(Gravity.CENTER);
                        dialogWindow.setAttributes(lp);
                        dialogDeleteProgram.show();
                    }
                } else {
                    mDialogLoader.stopProgressWithSuccess("方案提交成功", null,
                            new IDialogClickListener() {
                                @Override
                                public void onClick() {
                                    mDialogLoader.clearDialog();
                                }
                            });
                }
            }
        });

    }

    @Override
    public void pickGoodsSucceed() {
        _mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mDialogLoader.stopProgressWithSuccess("申请已提交",
                        "可在[我的领料单]中查看审批进度",
                        new IDialogClickListener() {
                            @Override
                            public void onClick() {
                                mDialogLoader.clearDialog();
                                EventBus.getDefault().post(
                                        new StartBrotherEvent
                                                (GoodsOrderDelegate.newInstance(mRepairId)));
                            }
                        });
                mDialogLoader.setConfirmText("查看我的领料单");
                mDialogLoader.showCancel(true);
            }
        });
    }

    @Override
    public void finishSucceed() {
        mDialogLoader.clearDialog();
    }

    @Override
    public void showNotWorkMaintain(final List<MaintainNotWorkWrapper> list) {
        if (list != null && !list.isEmpty()) {
            _mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mDialogLoader.clearDialog();

                    DialogMaintainNotWork dialogMaintainNotWork =
                            new DialogMaintainNotWork(_mActivity, list, new OnItemChooseListener<String>() {

                                @Override
                                public void onChoose(String s) {
                                    mDialogLoader.showProgressDialog(false,
                                            "正在提交", "请稍候...");
                                    mPresenter.commitNotWork(UserManager.getInstance().getToken(),
                                            mRepairTaskId, s);
                                }
                            });
                    Window dialogWindow = dialogMaintainNotWork.getWindow();
                    if (dialogWindow != null) {
                        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                        lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
                        lp.height = ScreenUtils.getScreenHeight() * 820 / 1024; // 高度
                        dialogWindow.setGravity(Gravity.CENTER);
                        dialogWindow.setAttributes(lp);
                        dialogMaintainNotWork.show();
                    }
                }
            });
        }
    }

    @Override
    public void commitNotWorkSucceed() {
        mDialogLoader.stopProgressWithSuccess("提交成功",
                null, new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        mDialogLoader.clearDialog();
                        EventBus.getDefault().post(new ReloadMaintainWorkDataEvent(mRepairId));
                    }
                });
    }

    @Override
    public void cancelFinishWorkSucceed() {
        _mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mDialogLoader.stopProgressWithSuccess("取消成功",
                        "请确认", new IDialogClickListener() {
                            @Override
                            public void onClick() {
                                mDialogLoader.clearDialog();
                            }
                        });
            }
        });
    }

    @Subscribe
    public void onGoodsEvent(GoodsEvent event) {
        mPresenter.getWorkData(UserManager.getInstance().getToken(),
                mRepairId, mVehicleSeriesId);
        mRadioGroup.check(mCheckId);
    }


}